<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-list="dialogInfo.btList"
    >
      <!--左右布局-->
      <!-- 条件栏 -->
      <div class="layui-row">
        <div class="layui-col-md6 SelectProductAddPrice">
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          />
          <DialogTable
            ref="productTable"
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            v-model:data="tableInfo.data"
            :api="tableInfo.api"
            :listen-height="false"
            :reserveSelection="true"
            v-model:query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="checkBox"
            @handleEvent="handleEvent"
          >
            <template v-slot:col-licenseNumber="scope">
              <p>{{ scope.row.licenseNumber || '-' }}</p>
              <p>{{ scope.row.brandName || '-' }}</p>
            </template>
            <template v-slot:col-commonName="scope">
              <p>{{ scope.row.commonName || '-' }}</p>
              <p>{{ scope.row.productCode || '-' }}</p>
              <p>{{ scope.row.alias || '-' }}</p>
            </template>
            <template v-slot:col-type="scope">
              <p>{{ scope.row.productTypeValue || '-' }}</p>
              <p>{{ scope.row.codeTypeValue || '-' }}</p>
              <p>{{ scope.row.productCategoryValue || '-' }}</p>
            </template>
            <template v-slot:col-standard="scope">
              <p>{{ scope.row.standard || '-' }}</p>
              <p>{{ scope.row.unitName || '-' }}</p>
            </template>
          </DialogTable>
        </div>
        <div
          class="layui-col-md6 SelectProductAddPrice SelectProductAddPriceRight"
          style="padding-left: 20px"
        >
          <p style="height: 33px; line-height: 33px" class="slip-edit">
            已选产品(当前供应商: {{ supplierName }})
          </p>
          <el-form :model="tableRightInfo" ref="tableForm" style="width: 100%">
            <DialogTable
              v-model:data="tableRightInfo.data"
              :check-box="false"
              :listen-height="false"
              :tab-index="true"
              :field-list="tableRightInfo.fieldList"
              :pager="false"
            >
              <template v-slot:col-licenseNumber="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
              <template v-slot:col-commonName="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
              <template v-slot:col-type="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.productCategoryValue || '-' }}</p>
              </template>
              <template v-slot:col-standard="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
              <template v-slot:col-price="scope">
                <el-form-item
                  v-if="scope.$index >= 0"
                  :prop="'data.' + scope.$index + '.price'"
                  :rules="
                    scope.$index >= 0
                      ? [
                          {
                            validator: systemConfig.product_price_can_be_zero
                              ? $validate.positiveMoneyZero
                              : $validate.positiveMoney,
                            trigger: 'blur',
                          },
                        ]
                      : []
                  "
                >
                  <el-input-number
                    controls-position="right"
                    style="width: 100%"
                    v-model="scope.row.price"
                    :min="0"
                    :max="99999999999999"
                    @change="changePrice($event, `data.${scope.$index}.price`)"
                    :precision="systemConfig.price_precision"
                    :step="1"
                  />
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </el-form-item>
              </template>
            </DialogTable>
          </el-form>
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="SelectProductAddPrice">
import { getSupplierProductPage } from '@/api/core.js'
import { getSupplierAll } from '@/api/core'
import { ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getSupplierProductPage,
  },
  showDialog: {
    type: Boolean,
    default: false,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  showStock: {
    type: Boolean,
    default: false,
  },
  supplierName: {
    type: String,
    default: '',
  },
  supplierId: {
    type: Number,
  },
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  query: {
    searchType: 'product',
    searchField: 'productId',
    showDisabled: true,
    type: 0,
    sort: 'create_time desc',
    ...props.query,
  },
  list: [
    // {
    //   type: 'input',
    //   label: '名称/别名/编码',
    //   value: 'keyword',
    //   event: search,
    // },
    {
      type: 'slip-select',
      label: '变更前供应商',
      value: 'supplierId',
      api: getSupplierAll,
      query: {
        supplierAuth: 'supplierId',
        sort: 'create_time desc',
        supplierIdNotIn: props.supplierId,
      },
      clearable: true,
      filterable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  fieldList: [
    { label: '通用名称\n编码\n别名', value: 'commonName', type: 'slot' },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
    },
    {
      label: '规格\n计量单位',
      value: 'standard',
      type: 'slot',
      width: '100px',
    },
    { label: '证号\n生产厂家', value: 'licenseNumber', type: 'slot' },
  ],
})
const tableRightInfo = ref({
  data: [],
  fieldList: [
    { label: '通用名称\n编码\n别名', value: 'commonName', type: 'slot' },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '价格', value: 'price', type: 'slot', width: 120 },
    { label: '证号\n生产厂家', value: 'licenseNumber', type: 'slot' },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '选择产品',
  width: '85%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref('')

onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    if (props.showStock) {
      tableInfo.value.fieldList.push({
        label: '库存数量',
        value: 'stockQty',
        type: 'column',
        formatter: proxy.$fn.qtyFormatter,
      })
    }
  })
})

function search() {
  proxy.$refs['productTable'].clearSelection()
  tableInfo.value.api = props.api
  tableInfo.value.refresh = Math.random()
  tableInfo.value.refresh = Math.random()
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
async function save() {
  // emits('input', data)
  if (tableRightInfo.value.data.length) {
    await proxy.$refs.tableForm.validate((valid) => {
      if (valid) {
        ElMessageBox.confirm(
          `是否将所选产品的默认供应商更换为新供应商${props.supplierName}`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            handleClose()
            setDefault('1')
            emits('callback', tableRightInfo.value.data)
          })
          .catch(() => {
            handleClose()
            setDefault('0')
            emits('callback', tableRightInfo.value.data)
          })
      }
    })
  } else {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择产品',
    })
  }
}
function setDefault(val) {
  tableRightInfo.value.data.forEach((item) => {
    item.isDefault = val
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableRightInfo.value['data'] = []
      proxy.$nextTick(() => {
        tableRightInfo.value['data'] = data
      })
      dialogInfo.value.btList[1].disabled = !data.length
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
</script>

<style scoped>
/* :deep(.SelectProductAddPrice){
        height: 355px;
        display: flex;
        flex-direction: column;
    }
    :deep(.SelectProductAddPriceRight .page-table > .el-table){
        max-height: 253px;
        overflow: auto;
    } */
</style>
